package cn.fx.framework.exception;

import cn.fx.framework.core.CodeMessage;
import cn.fx.framework.utils.New;
import cn.fx.framework.utils.StringUtils;

import java.util.List;
import java.util.Map;

/**
 * 异常其类，所有框架自定义的异常及使用此框架的应用所定义异常时都可继承此类
 * @author fxcn
 * @date 2024-9-29
 */
public class BaseException extends RuntimeException {
    protected int code;
    private String msg;
    private List<Object> msgIndexArgs;
    private Map<String, Object> msgMapArgs;

    public BaseException(String msg){
        super(msg);
    }
    public BaseException(int code, String msg){
        super(msg);
        this.code = code;
    }


    public BaseException kv(String key, Object value){
        if(null == this.msgMapArgs){
            this.msgMapArgs = New.map();
        }
        this.msgMapArgs.put(key, value);
        return this;
    }

    public BaseException v(Object object){
        if(null == this.msgIndexArgs){
            msgIndexArgs = New.list();
        }
        this.msgIndexArgs.add(object);
        return this;
    }

    public Map<String, Object> getMsgMapArgs() {
        return msgMapArgs;
    }

    public List<Object> getMsgIndexArgs() {
        return msgIndexArgs;
    }




    public int getCode() {
        return code;
    }
    public void setCode(int code) {
        this.code = code;
    }

    public void setMsg(String msg){
        this.msg = msg;
    }
    public String getMsg(){
        return this.msg;
    }

    /**
     * 获取异常消息
     * 1、如果msg为空，组织链式错误消息返回；
     * 2、如果msgIndexArgs不为空，格式化msg返回；
     * 3、如果msgMapArgs不为空，格式化msg返回。
     * @return
     */
    @Override
    public String getMessage() {
        if(null == msg){
            List<String> list = New.list();
            list.add(super.getMessage());
            Throwable throwable = this.getCause();
            while(throwable!=null){
                list.add(throwable.getMessage());
                throwable = throwable.getCause();
            }
            //异常链若只有一个，则直接返回消息，不对消息做任何处理
            if(list.size() == 1){
                msg = list.get(0);
            }else {
                StringBuilder s = new StringBuilder("异常消息：");
                for (int i = 0; i < list.size(); i++) {
                    if (i > 0) {
                        s.append(" due to exception ");
                    }
                    s.append("[").append(list.get(i)).append("]");
                }
                msg = s.toString();
            }
        }
        if(null != msgIndexArgs && msgIndexArgs.size() > 0){
            //如果List:msgIndexArgs不为空，返回format格式化数组的值
            return StringUtils.format(msg, msgIndexArgs.toArray());
        }else if(null != msgMapArgs && msgMapArgs.size() > 0){
            //如果仅有一条错误消息，使用msg与map格式化
            return StringUtils.formatNamedParameterByArrayArgs(msg, msgMapArgs);
        }
        return msg;
    }

    @Override
    public String toString() {
        return this.getMessage();
    }
}
